package com.example.demo01.repository.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.example.demo01.domain.Ingredient;
import com.example.demo01.repository.IngredientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;




@Repository
public class JdbcIngredientRepository implements IngredientRepository {
	private JdbcTemplate jdbc;
	@Autowired
	public JdbcIngredientRepository(JdbcTemplate jdbc) {
		this.jdbc=jdbc;
	}
	//查询id，name，type
	@Override
	public Iterable<Ingredient> findAll() {
		return jdbc.query("select id,name,type from Ingredient", this::mapRowToIngredient);
	}
//查询id，name，type通过id
	@Override
	public Ingredient findById(String id) {
		return jdbc.queryForObject("select id,name,type from Ingredient where id=?", this::mapRowToIngredient,id);
	}
//保存数据
	@Override
	public Ingredient save(Ingredient ingredient) {
		jdbc.update("insert into Ingredient (id,name,type) values(?,?,?,?)",
				ingredient.getId(),
				ingredient.getName(),
				ingredient.getType().toString());
		return ingredient;
	}
	//将结果映射到Ingredient对象上
	private Ingredient mapRowToIngredient(ResultSet rs,int rowNum) throws SQLException {
		return new Ingredient(
				rs.getString("id"),
				rs.getString("name"),
				Ingredient.Type.valueOf(rs.getString("type")));
	}

}
